local xclient = {}

print("====XConsole Server, a LUA console over wifi.======")
print("Author: openthings@163.com. copyright&GPL V2.")
print("starting...2014-12-04. V0.31. HEAP:"..node.heap())

tCount=0
tBreak=0
tStatus=0
apIndex=1
apMax=2
cServer = "192.168.199.200"
cPort = 8090
cc = nil
who="ESP8266_SMARTLUMP"

local apTable={{"HiWiFi_SMT","87654321","192.168.199.200"},{"NETGEAR71","shinyphoenix155","192.168.1.100"}}

function xclient.who()
	print(who)
end

function xclient.apl()
	for i=1,#apTable do
		print("SSID:"..apTable[i][1]..","..apTable[i][2])
	end
end

function xclient.s_output(str)
	if (cc~=nil) then cc:send(str) end
end

function xclient.start()
	print("Wifi AP connected. IP:"..wifi.sta.getip())
	print("Remote Service console connected.")
	node.output(xclient.s_output,1)

	cc=net.createConnection(net.TCP,false)
	cc:on("receive", function(conn, pl)
		if (conn==nil) 	then print("conn is nil.") 
		else 
			print("REV:"..pl) 
			node.input(pl) 
		end
	end)
	cc:on("disconnection",function(conn) 
		node.output(nil) 
	end)

	cc:connect(80,"192.168.1.66")
	cc:send("Hello.\r\n")
	print("xconsole client running at: 8090,Heap: "..node.heap())
end

function xclient.checkIP()
	if tBreak==1 then tmr.stop() end
	if wifi.sta.getip()=="0.0.0.0" then
		if (tStatus==1) then 
			tStatus=0
			net.server.close()
			tmr.alarm(2000, 1, xclient.checkIP)
		end
		print(string.format("%d:Connect AP, Waiting...",tCount)) 
		tCount=tCount+1
		if tCount>5 then
			print("Trying SSID:"..apTable[apIndex][1]..","..apTable[apIndex][2])
			wifi.setmode(wifi.STATIONAP)
			wifi.sta.config(apTable[apIndex][1],apTable[apIndex][2])
			wifi.sta.connect()
			tCount=0
			apIndex = apIndex+1
			if apIndex>apMax then apIndex=1 end
		end
	else
		if tStatus==0 then
			xclient.startServer()
			tmr.alarm(30000, 1, xclient.checkIP)
			tStatus = 1
		else
			print("*Tic: ["..tmr.now().."] Wifi AP OK. Server IP:"..wifi.sta.getip())
		end
		if (cc~=nil) then cc:send("#DATA:a sensor data.") end
	end
end

function xclient.waitstart()
	tmr.alarm(2000, 1, xclient.checkIP)
end

xclient.waitstart()

return xclient
